package py.com.fms.fms.session.maintenances;

// External classes imports 
// Java Classes
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

// Seam Classes
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

//project classes imports
import py.com.fms.fms.bean.BankAccountsBean;
import py.com.fms.fms.bean.BranchBean;
import py.com.fms.fms.bean.EnterpriseBean;
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.fms.persistence.services.BankAccountsServices;
import py.com.fms.fms.persistence.services.BranchServices;
import py.com.fms.fms.persistence.services.EnterpriseServices;
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.exception.CommonException;
import py.com.fms.session.ParamHolder;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;
import py.com.fms.utilities.ConvertAssistant;
import py.com.fms.utilities.DateAssistant;

@SuppressWarnings("unused")
@Name("editBankAccount")
@Scope(ScopeType.SESSION)
public class EditBankAccounts {

	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private boolean editMode;
	private String initVar;
	private Date today = null;

	// Task Attendees Attributes 
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{paramHolder}")
	private ParamHolder param;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	@In Credentials credentials;
	@In Identity identity;
	private UsersBean user;
	
	// Attribute used for saving and deleting
	private BankAccountsBean bankAccount;
	
	// Services
	private EnterpriseServices enSrv;
	private BankAccountsServices baSrv;
	private UsersServices usSrv;
	
	// Collection of monedasBean
	private Collection<BankAccountsBean> allBankAccount;

	// Attribute used for editing or updating
	private BankAccountsBean editBankAccount;
	
//	Necessary Attributes;
	private EnterpriseBean entName = null;
	private EnterpriseBean entCod;
	private Long entId;

	
	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] 
	 * [[[[[[[[[[-------------]]]]]]]]]]
	 * @throws CommonException 
	 */

	// Used to initialize information from a variable
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) {
			this.loadUserData();
			this.initBeans();
			this.initServices();
			this.initAssistants();
			this.initCollections();
			this.loadDataGrid();

			
		}
		this.setInitVar(null);
		System.out.println("OUT");
				
	}
	public void loadParams() throws CommonException{
		this.param.initData();
		this.param.loadParams();
	}
	
	private void loadUserData() throws CommonException{
		if(user == null){
		   user = new UsersBean();
		}
		if(usSrv == null){
		   usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		if(credentials != null){
			System.out.println("Credenciales Encontradas");
			this.getUser().setUserName(credentials.getUsername());
			System.out.println("User Name: " + this.getUser().getUserName());
			user = usSrv.getUserDataByName(this.getUser().getUserName());
			this.setUser(user);
			System.out.println("User: " + this.getUser());
		}else{	
			System.out.println("Credenciales Nulas");
		}
	}
	
	public void initBeans(){
		
		if (bankAccount == null){
			bankAccount = new BankAccountsBean();
			bankAccount.setStatus(true);
		}
		
		if (editBankAccount == null){
			editBankAccount = new BankAccountsBean();
		}
		if (entCod == null){
			entCod = new EnterpriseBean();
		}
		
		if (entName == null){
			entName = new EnterpriseBean();
		}
		
		
	}
	
	public void initServices() throws CommonException{
		
		if (enSrv == null){
			enSrv = new EnterpriseServices(this.sqlMap.getConfig());
		}
		
		if (baSrv == null){
			baSrv = new BankAccountsServices(this.sqlMap.getConfig());
		}
		
				
	}
	
	public void initAssistants(){
		
		
		if(aid == null){
			aid = new WithinHolder();
		}
		
		if(param == null){
			param = new ParamHolder();
		}
		
		if(convert == null){
			convert = new ConvertAssistant();
		}
		
	}
	
	public void initCollections(){
		if(allBankAccount == null){
			allBankAccount = new ArrayList<BankAccountsBean>();
		}


	}
	
	public void cleanData(){

		bankAccount = null;
		editBankAccount = null;
		entCod = null;
		entName = null;
		user = null;
		
		enSrv = null;
		baSrv = null;
		usSrv = null;

		aid = null;
		param = null;
		convert = null;

		allBankAccount = null;
	}

	// Used to load a grid using a collection
	private void loadDataGrid() {
		try {
			this.setAllBankAccount (baSrv.getAllBankAccount());
			for (BankAccountsBean bankAccount : this.getAllBankAccount()) {
				System.out.println(bankAccount.getAccountNumber());
			}
		} catch (CommonException e) {
			e.printStackTrace();
		}
	}

	// Used to cancel
	public String cancelData() throws CommonException {
		this.facesMessages.clear();
		this.setInitVar("S");
		this.cleanData();
		this.initData();
		return null;
	}
		

	// Used for data saving process
	public String saveNewData() throws ParseException {
		try {
			this.facesMessages.clear();
			BankAccountsBean newBankAccount = new BankAccountsBean();
			this.today =  DateAssistant.getHoleDateTime();
            
			if (this.getAllBankAccount() == null) {
				System.out.println("this.getAllBankAccount() == null");
				throw new CommonException("error.fms.menu.error.countrynotexist");
			}
			System.out.println("Before saveNewData");
			// Setting field values
			newBankAccount.setIdEnt(user.getIdEnt());
			newBankAccount.setIdBank(this.getBankAccount().getIdBank());
			newBankAccount.setAccountNumber(this.convert.convertField(this.getBankAccount().getAccountNumber()));
			newBankAccount.setRef(this.convert.convertField(this.getBankAccount().getRef()));
			newBankAccount.setIdCurrency(this.getBankAccount().getIdCurrency());
			newBankAccount.setIdAccountType(this.getBankAccount().getIdAccountType());
			newBankAccount.setIdAccounting(this.getBankAccount().getIdAccounting()) ;
			newBankAccount.setIdUserIns(user.getId());
			newBankAccount.setStartDate(this.today);
			newBankAccount.setStatus(this.getBankAccount().getStatus());
            
			System.out.println(this.today);
			newBankAccount.setIdUserIns(user.getId());
            
			baSrv.saveNewBankAccount(newBankAccount);
			
		} catch (CommonException e) {
			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO INSERTAR. " + e.getMessage());
			log.error(e);
		}
		return "";
	}
	
	// Retrieving data for updating
	public void dataToEdit(Long id){
		System.out.println("id = " + id.toString());
		for (BankAccountsBean bean : this.getAllBankAccount()) {
			if(bean.getId() == id){
				this.setEditBankAccount(bean);
				return;
			}			
		}	
	}
	
	public void dataToEditUpd() throws ParseException{
		try {
			baSrv.updateBankAccount(this.getEditBankAccount());
		} catch (CommonException e) {
			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO ACTUALIZAR EL REG. " + e.getMessage());
			log.error(e);
		}
	}
	
	public void dataToDelete(Long id){
		for (BankAccountsBean bean: this.getAllBankAccount()){
			if (bean.getId() == id) {
				try {
					baSrv.deleteBankAccountById(bean.getId());
				} catch (Exception e) {
					this.facesMessages.add(Severity.ERROR, e.getMessage());
					System.out.println("NO SE BORRAR EL REGISTRO. " + e.getMessage());
					log.error(e);
				}
			}
			
		}
		this.setInitVar("S");
	}

	// Getters and Setters

	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}

	public boolean isEditMode() {
		return editMode;
	}

	public void setEditMode(boolean editMode) {
		this.editMode = editMode;
	}

	public String getInitVar() {
		return initVar;
	}

	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}
	
	public UsersBean getUser() {
		return user;
	}

	public void setUser(UsersBean user) {
		this.user = user;
	}
	public BankAccountsBean getBankAccount() {
		return bankAccount;
	}
	public void setBankAccount(BankAccountsBean bankAccount) {
		this.bankAccount = bankAccount;
	}
	public Collection<BankAccountsBean> getAllBankAccount() {
		return allBankAccount;
	}
	public void setAllBankAccount(Collection<BankAccountsBean> allBankAccount) {
		this.allBankAccount = allBankAccount;
	}
	public BankAccountsBean getEditBankAccount() {
		return editBankAccount;
	}
	public void setEditBankAccount(BankAccountsBean editBankAccount) {
		this.editBankAccount = editBankAccount;
	}
}
